package node

import (
	"engine/db"
	"engine/eng_cfg"
	"engine/log"
	"gitee.com/ameise84/e3dds"
	"gitee.com/ameise84/e3utils/common"
	"github.com/spf13/viper"
)

var (
	_node *node
)

func init() {
	_node = &node{}
}

type node struct {
	common.Service
	dbUse bool
}

func (ts *node) Start() error {
	return ts.Service.Start(func() (err error) {
		//启动数据库
		if _, err = db.Start(); err != nil { //主数据库
			return
		}
		defer func() {
			if err != nil {
				db.Stop()
			}
		}()
		opts := e3dds.DefaultDcsOptions()
		opts.SetCallSlow(viper.GetInt64(eng_cfg.NodeCallSlow))
		opts.SetCallTimeOut(viper.GetInt64(eng_cfg.NodeCallTimeout))
		opts.GetRPCOptions().SetAddr(viper.GetString(eng_cfg.NodeRpcAddr)).SetReadTimeout(viper.GetInt64(eng_cfg.NodeRpcTimeoutRead)).SetWriteTimeout(viper.GetInt64(eng_cfg.NodeRpcTimeoutWrite))
		opts.GetDiscoOptions().SetKind(viper.GetString(eng_cfg.NodeDDSKind)).SetAddr(viper.GetStringSlice(eng_cfg.NodeDDSAddr)).SetKeepAlive(viper.GetInt(eng_cfg.NodeDDSKeepAlive))
		//服务启动
		return e3dds.Start(opts)
	})
}

func (ts *node) Stop() {
	ts.Service.Stop(func() {
		e3dds.Stop() //关闭服务
		if ts.dbUse {
			db.Stop()
		}
		log.GetLogger().Info("node stopped").Println()
	})
}

func (ts *node) IsStopped() bool {
	return ts.Service.IsStopped()
}
